<template>
  <page-container title="修改头像">
    <el-row>
      <el-col :span="12">
        <el-upload
          style="margin-bottom: 20px"
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onUploadFile"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <el-button
          @click="uploadRef.$el.querySelector('input').click()"
          type="primary"
          :icon="Plus"
          size="large"
        >
          选择图片
        </el-button>
        <el-button
          @click="onUploadImage"
          type="success"
          :icon="Upload"
          size="large"
        >
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </page-container>
</template>

<script setup>
import { userUploadAvatarService } from '@/api/upload'
import { ref, computed } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { userGetInfoService2 } from '@/api/user'

const  user  = computed(() => useUserStore().user)

const imageUrl = ref(user.value.avatar)
const uploadRef = ref()
const upImage = ref(null)
const onUploadFile =  (uploadFile) => {
  //使用FlieReader读取图片
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  upImage.value = uploadFile.raw

  
}
const onUploadImage = async() => {
  console.log("666" + upImage.value);
  
  const fd = new FormData()
  fd.append("image", upImage.value)
  await userUploadAvatarService(fd)
  const { data } = await userGetInfoService2()
  ElMessage({ type: 'success', message: '更换头像成功' })
  // useUserStore().setUser(data)
  useUserStore().setImage(imageUrl)
  console.log("-----",user);
  
}


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 278px;
  height: 278px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>
